All files / app/api/admin/users/[id] route.ts

85.71% Statements 24/28
100% Branches 8/8
100% Functions 2/2
85.71% Lines 24/28

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76          1x 1x 1x                     1x   3x 3x 1x     2x 2x 2x   2x 1x     1x                             1x   3x 3x 1x     2x 2x     2x 2x 1x     1x   1x                  
/**
 * Admin User API - Get and Delete Individual User
 * @see JCN-4 Phase 7: Wire E2E Tests to Real Backend
 * @see JCN-23 Authorization fix
 */
import { NextRequest, NextResponse } from "next/server";
import { getUser, deleteUser } from "@/lib/cognito-admin";
import { requireSuperAdmin, forbiddenResponse } from "@/lib/amplify-server-utils";
 
interface RouteContext {
  params: Promise<{ id: string }>;
}
 
/**
 * GET /api/admin/users/[id]
 * Get a specific user by ID (Cognito username)
 * Requires: super_admin role
 */
export async function GET(request: NextRequest, context: RouteContext) {
  // Authorization check
  const auth = await requireSuperAdmin();
  if (!auth.authorized) {
    return forbiddenResponse(auth.error);
  }
 
  try {
    const { id } = await context.params;
    const user = await getUser(id);
 
    if (!user) {
      return NextResponse.json({ error: "User not found" }, { status: 404 });
    }
 
    return NextResponse.json({ user });
  } catch (error) {
    console.error("Error getting user:", error);
    return NextResponse.json(
      { error: "Failed to get user", details: (error as Error).message },
      { status: 500 }
    );
  }
}
 
/**
 * DELETE /api/admin/users/[id]
 * Delete a user (permanent deletion from Cognito)
 * Requires: super_admin role
 */
export async function DELETE(request: NextRequest, context: RouteContext) {
  // Authorization check
  const auth = await requireSuperAdmin();
  if (!auth.authorized) {
    return forbiddenResponse(auth.error);
  }
 
  try {
    const { id } = await context.params;
 
    // Check if user exists
    const user = await getUser(id);
    if (!user) {
      return NextResponse.json({ error: "User not found" }, { status: 404 });
    }
 
    await deleteUser(id);
 
    return NextResponse.json({ success: true, message: "User deleted" });
  } catch (error) {
    console.error("Error deleting user:", error);
    return NextResponse.json(
      { error: "Failed to delete user", details: (error as Error).message },
      { status: 500 }
    );
  }
}